<?php


namespace app\api\controller;


use app\common\model\ApplicationBanker;
use app\common\model\BetsLog;
use app\common\model\BetsLogSubscribe;
use app\common\model\GamblerKing;
use app\common\model\GamblerKingInvestmentUser;
use app\common\model\Lottery;
use app\common\model\LotteryOdds;
use app\common\model\LotteryPlay;
use app\common\model\LotteryResult;
use app\common\model\LotteryRound;
use app\common\model\Member;
use app\common\model\UserLevel;
use GatewayClient\Gateway;
use think\Cache;
use think\Controller;
use think\Db;
use think\Queue;


class Lotteryapi extends Controller
{
    public function create_round()
    {

        $lottery_list=Lottery::all(['status'=>1]);

        foreach ($lottery_list as $k=>$v){
            if($v['id']!=22){
                $is = LotteryRound::where(["day_round" =>$v['round_number'],'create_time'=>['gt',getTodayStart()], 'lottery_id' => $v['id']])->count();
            }else{
                if( TIME_NOW > (getTodayStart()+21*3600) ){
                    $is = LotteryRound::where(["day_round" =>1,'create_time'=>['gt',getTodayStart()+21*3600], 'lottery_id' => $v['id']])->count();
                }else{
                    $is=1;
                }

            }

            if(!$is){
                $new_arrs=[];
                include_once(ROOT_PATH . 'extend/createround/' . $v->cate->symbol . '.php');
                $_zhushuyzclass = "createround\\{$v->cate->symbol}";
                $_obj = new $_zhushuyzclass();

                $arrs=$_obj->check($v['symbol']);
                foreach ($arrs as $ke => $va){
                    $is = LotteryRound::where(["round" => $va['round'], 'lottery_id' => $v['id']])->count();
                    if (empty($is)) {
                        $new_arrs[] = $va;

                    }
                }
                if($new_arrs){
                    LotteryRound::insertAll($new_arrs);
                }
            }

        }



    }


    /**
     * 采集开奖结果
     */
    public function select_1()
    {
        $jobHandlerClassName  = 'app\api\job\Bets';

        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName  	  = "BetsJobQueue";
        LotteryRound::where("start_time <= unix_timestamp(now()) and state=1 ")->update(["state" => 2]);
        LotteryRound::where("end_time < unix_timestamp(now()) ")->update(["state" => 3]);
        Gateway::$registerAddress = getConfig('websocket_ip').':1236';
        $lottery_list=Lottery::all(['status'=>1]);
        $new_arrs=[];
        foreach ($lottery_list as $k=>$v){
            include_once(ROOT_PATH . 'extend/collectresult/' . $v->cate->symbol . '.php');
            $_zhushuyzclass = "collectresult\\{$v->cate->symbol}";
            $_obj = new $_zhushuyzclass();

            $arrs=$_obj->check($v['symbol']);
            foreach ($arrs as $ke => $va) {
                $count = LotteryResult::where(["round" => $va['round'], 'lottery_id' => $v['id']])->count();
                if ($count==0 ) {
                    $message= [
                        'type'=>1,
                        'time'=>date('Y-m-d H:i:s')
                    ];
                    $message = json_encode($message);
                    $group=$v->symbol.'_'.$v['id'];
                    Gateway::sendToGroup($group, $message);

                    $bets_ids=BetsLog::where(["round" => $va['round'], 'lottery_id' =>  $v['id'],'state'=>1])->column('id');
                    if($bets_ids){
                        foreach ($bets_ids as $key=>$val){
                            d($val);
                            Queue::push($jobHandlerClassName,$val, $jobQueueName);
                        }
                    }
                    $new_arrs[]=$va;
                }
            }

        }
        if($new_arrs){
            LotteryResult::insertAll($new_arrs);
        }


    }

    /***
     * 11选5公共方法
     */
    private function common_select($name, $type, $cate)
    {
        if ($name == 'sd') {
            //山东
            $res = "http://api.caipiaokong.cn/lottery/?name=" . $name . "syydj&format=json&uid=1369988&token=fd2493980afc452c799a031546d6e33c6937a79f";
        } else {
            $res = "http://api.caipiaokong.cn/lottery/?name=" . $name . "syxw&format=json&uid=1369988&token=fd2493980afc452c799a031546d6e33c6937a79f";
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $res);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);
        if (!empty($result)) {
            $result = json_decode($result, true);
            //dump($result);
            ksort($result);
            foreach ($result as $k => $v) {
                $count = LotteryResult::where(["round" => $k, 'lottery_id' => $type])->count();
                if (empty($count) && $v['number'] && $v['dateline']) {
                    $data = array(
                        'lottery_id' => $type,
                        'round' => $k,
                        'day_round' => substr($k, -2),
                        'number' => $v['number'],
                        'dateline' => $v['dateline'],
                        'create_time' => time(),
                        'source' => '第三方采集',
                        'cate_id' => $cate
                    );
                    LotteryResult::create($data);
                }
            }
        }
    }

    /***
     * 投注结算
     */

    public function bet_settlement()
    {

        $list = BetsLog::all(['state' => 1]);
        $member_list=[];
        $members=Member::all(['status'=>1]);
        foreach($members as $k=>$v){
            $member_list[$v['id']]=$v;
        }
        foreach ($list as $k => $v) {
            $lottery_result = LotteryResult::get(['lottery_id' => $v['lottery_id'], 'round' => $v['round']]);
            if ($lottery_result) {

                Db::startTrans();
                try {

                    $v->new_settlement($lottery_result,$member_list);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    echo $e->getMessage() . '</br>';
                }
            }
        }
    }


    /***
     * 预约投注结算
     */

    public function synchro_bet_settlement()
    {
        $list = BetsLogSubscribe::all(['state' => 1,'end_time'=>['lt',TIME_NOW]]);

        foreach ($list as $k => $v) {
            $lottery_result = LotteryResult::get(['lottery_id' => $v['lottery_id'], 'round' => $v['round']]);
            if ($lottery_result) {
                Db::startTrans();
                try {

                    $v->new_settlement($lottery_result);

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    echo $e->getMessage() . '</br>';
                }
            }
        }
    }


    /***
     * 预约同步下注下注
     */
    public function  synchro_bet(){
        $list = BetsLogSubscribe::all(['is_synchro' => 1,'synchro_state'=>0,'start_time'=>['lt',TIME_NOW]]);

        foreach ($list as $k => $v) {

        Db::startTrans();
        try {

            $v->subscribe_add_lottery($v);
            $v->synchro_state=1;
            $v->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage() . '</br>';
        }

        }

    }


    /***
     * 止损分红
     */
    public function reduce_bonus()
    {
        $list = GamblerKing::where(['state' => 2, 'balance' => ['gt',0]])->select();
        //        $list=GamblerKingInvestmentUser::where(['state'=>3])->select();
        //        dd($list);
        foreach ($list as $k => $v) {
            Db::startTrans();
            $info=GamblerKingInvestmentUser::where(['king_id'=>$v['id'],'state'=>3])->lock(true)->find();
            $count=BetsLog::where(['state'=>1,'user_investment_id'=>$info['id']])->count();
            if($count){
                Db::commit();
                continue;
            }

            try {
                if($info){
                    $v->get_reward();
                }

                // echo 1;die;;
                Db::commit();
                echo 1;
            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollback();
            }


        }
    }



    /***
     * 止赢分红
     */
    public function winn_bonus()
    {
        $sql="SELECT * FROM `tp_gambler_king_investment_user` WHERE  `state` = 3  AND `stop_win_money_first` >=stop_win_money";
        $list=Db::query($sql);


        foreach ($list as $k => $v) {

            $count=BetsLog::where(['state'=>1,'user_investment_id'=>$v['id']])->count();
            if($count){
                continue;
            }

            Db::startTrans();
            try {
                $info=GamblerKingInvestmentUser::where(['id' => $v['id'],'state'=>3])->lock(true)->find();
                if($info){
                    $info->get_reward();
                }

                // echo 1;die;;
                Db::commit();
                echo 1;
            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollback();
            }


        }
    }


    /***
     * 更新赔率
     */

    public function  update_odds(){
        $lottey_list=Lottery::all(['status'=>1]);


        $max_point=getConfig('max_point');
        $banker=ApplicationBanker::get(1);
        foreach ($lottey_list as $k=>$v){
            $play_list=LotteryPlay::all(['status'=>1,'cate_id'=>$v['cate_id']]);
                foreach ($play_list as $ke=>$va){
//                    Cache::set('lottery_'.$v['id'].'_play_'.$va['id'],null);
                    d(Cache::get('lottery_'.$v['id'].'_play_'.$va['id']));
                    if(!Cache::get('lottery_'.$v['id'].'_play_'.$va['id'])){
                        $url=$banker->account_address.'/api/external/rebaterate/';
                            $url.=$v['third_lottery_id'].'/'.$va['platform_play_id'].'/'.$max_point;
                            $res=mycurl($url);
                            $res=json_decode($res,true);
                            if($res){
                                foreach ($res['data']['points'] as $key=>$val){
                                    if($val['persent']==0){
                                        if(strstr($val['points'], '|')){
                                            $arr=explode('|',$val['points']);
                                            $points=0;
                                            switch ($va['platform_play_id']){
                                                case 3456:
                                                    $arr2=[3,4,18,19];
                                                    $arr3=[5,6,16,17];
                                                    $arr4=[7,8,14,15];
                                                    $arr5=[9,10,12,13];
                                                    if( in_array($va['number'],$arr2)  ){
                                                        $points=$arr[0];
                                                    }elseif (in_array($va['number'],$arr3) ){
                                                        $points=$arr[1];
                                                    }elseif (in_array($va['number'],$arr4) ){
                                                        $points=$arr[2];
                                                    }elseif (in_array($va['number'],$arr5) ){
                                                        $points=$arr[3];
                                                    }else{
                                                        $points=$arr[4];
                                                    }
                                                    break;
                                                case 3460:
                                                    if($va['number']=='大' || $va['number']=='双'){
                                                         $points=$arr[0];
                                                    }else{
                                                        $points=$arr[1];
                                                    }
                                                    break;
                                            }
                                            $va->mult=$points;
                                            $va->save();
                                            $info=LotteryOdds::get(['play_id'=>$va['id'],'lottery_id'=>$v['id'],'third_play_id'=>$va['platform_play_id']]);
                                            if($info){
                                                $info->odds=$points;
                                                $info->save();
                                            }else{
                                                LotteryOdds::create([
                                                    'play_id'=>$va['id'],
                                                    'lottery_id'=>$v['id'],
                                                    'third_play_id'=>$va['platform_play_id'],
                                                    'odds'=>$points

                                                ]);
                                            }
                                        }else{
                                            $points=$val['points'];
                                            $info=LotteryOdds::get(['play_id'=>$va['id'],'lottery_id'=>$v['id'],'third_play_id'=>$va['platform_play_id']]);
                                            if($info){
                                                $info->odds=$val['points'];
                                                $info->save();
                                            }else{
                                                LotteryOdds::create([
                                                    'play_id'=>$va['id'],
                                                    'lottery_id'=>$v['id'],
                                                    'third_play_id'=>$va['platform_play_id'],
                                                    'odds'=>$val['points']

                                                ]);
                                            }
                                            $va->mult=$points;
                                            $va->save();
                                        }

                                        Cache::set('lottery_'.$v['id'].'_play_'.$va['id'],$points,86400*7);
                                    }
                                }
                            }


                     }

                }

        }
    }


}